import { ExternalOption, RollifyConfigure } from '../typing'
import { isArray, isFunction, isRegexp, isString } from 'node-aux'
import { NullValue } from 'rollup'

const setExternal = function (
    external: ExternalOption,
    source: string,
    importer: string | undefined,
    isResolved: boolean
) {
    if (isArray(external)) {
        return external.some((pattern) => {
            if (isRegexp(pattern)) {
                return pattern.test(source)
            }
            if (isString(pattern)) {
                return source.includes(pattern)
            }
            if (isFunction(pattern)) {
                return pattern(source, importer, isResolved)
            }
        })
    }
    if (isString(external)) {
        return source.includes(external)
    }
    if (isRegexp(external)) {
        return external.test(source)
    }
    if (isFunction(external)) {
        return external(source, importer, isResolved)
    }
    return external
}

export const externalConfigure = function <T extends RollifyConfigure>(userConfig: T) {
    const { external = [] } = userConfig
    return {
        name: 'external',
        configure: () => {
            return (
                source: string,
                importer: string | undefined,
                isResolved: boolean
            ): boolean | NullValue => {
                return setExternal(external, source, importer, isResolved)
            }
        }
    }
}
